package com.chinaedu.oc.serv.product.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinaedu.oc.bo.ProductLineQuery;
import com.chinaedu.oc.bo.ProductQuery;
import com.chinaedu.oc.constant.Constant;
import com.chinaedu.oc.dao.product.ProductDao;
import com.chinaedu.oc.dao.productline.ProductLineDao;
import com.chinaedu.oc.dao.productline.ProductLineDepartmentDao;
import com.chinaedu.oc.dao.productline.ProductLineKeyDao;
import com.chinaedu.oc.po.dto.PubOutputDto;
import com.chinaedu.oc.po.product.Product;
import com.chinaedu.oc.po.productline.ProductLine;
import com.chinaedu.oc.po.productline.ProductLineDepartment;
import com.chinaedu.oc.po.productline.ProductLineKey;
import com.chinaedu.oc.po.productline.dto.AddProductLineInput;
import com.chinaedu.oc.po.productline.dto.AddProductLineOutput;
import com.chinaedu.oc.po.productline.dto.ConfigProductLineKeyInput;
import com.chinaedu.oc.po.productline.dto.ConfigProductLineKeyOutput;
import com.chinaedu.oc.po.productline.dto.CreateProductLineKeyOutput;
import com.chinaedu.oc.po.productline.dto.QueryProductLineInput;
import com.chinaedu.oc.po.productline.dto.QueryProductLineOutput;
import com.chinaedu.oc.po.productline.dto.StartUseProductLineInput;
import com.chinaedu.oc.serv.product.ICodeCreate;
import com.chinaedu.oc.serv.product.IProductLine;
import com.chinaedu.oc.util.common.CheckNull;
import com.chinaedu.oc.util.common.CheckParamException;
import com.chinaedu.oc.util.common.IdCreater;
import com.chinaedu.oc.util.common.StringUtil;
import com.chinaedu.oc.util.plugin.PageParams;

/**
 * 
 * @Description: TODO
 * @author A18ccms a18ccms_gmail_com
 * @date 2017年5月9日 下午5:43:31
 *
 */
@Service("ProductLineServ")
public class IProductLineImpl implements IProductLine {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	ProductLineDao productLineDao;
	@Autowired
	ProductLineKeyDao productLineKeyDao;
	@Autowired
	ProductDao productDao;
	@Autowired
	ProductLineDepartmentDao productLineDepartmentDao;
	@Autowired
	ICodeCreate codeCreateServ;

	/**
	 * 添加或者更新产品线
	 * 
	 * @throws CheckParamException
	 */
	@Override
	public AddProductLineOutput addOrUpdateProductLine(AddProductLineInput input) throws CheckParamException {

		AddProductLineOutput out = new AddProductLineOutput();

		ProductLine productLine = input.getProductLine();
		CheckNull cn = new CheckNull();
		cn.checkNull(productLine, "portalAddress", "name", "businessType");
		
		if(productLine.getName().length() >= 20) {
			throw new CheckParamException("产品线名称过长");
		}
		if(!StringUtil.isBlack(productLine.getHeader()) && productLine.getHeader().length() >= 20) {
			throw new CheckParamException("负责人名称过长");
		}
		if(!StringUtil.isBlack(productLine.getComments()) && productLine.getComments().length() >= 140) {
			throw new CheckParamException("备注过长");
		}

		String id = "";
		// 添加
		if (StringUtil.isBlack(productLine.getId())) {

			// 添加productLine
			id = IdCreater.getId();
			productLine.setId(id);
			productLine.setCreater(input.getUser());
			productLine.setCreateDate(new Timestamp(System.currentTimeMillis()));
			productLine.setStartUse(Constant.FORBID_USE + "");
			productLine.setEffStatus(Constant.YES_1); 
			productLine.setEffDate(new Timestamp(System.currentTimeMillis()));
			
			productLine.setCode(this.getCode(productLine.getBusinessType()));
			out.setProductLine(productLine);
			productLineDao.insertProductLine(productLine);
			
		} else {
			id = productLine.getId();
			
			ProductLine pl = productLineDao.selectProductLineById(productLine.getId());
			
			PageParams<Product> params = new PageParams<Product>();
			ProductQuery pro = new ProductQuery();
			pro.setProductLine(id);
			params.setParam(pro);
			List<Product> list = productDao.selectProductByField(params );
			if(list != null && list.size() >= 1) {
				productLine.setBusinessType(pl.getBusinessType());
				productLine.setCode(pl.getCode());
			}else {
				//如果业务类型变了，则要重新生成code
				if(!productLine.getBusinessType().equals(pl.getBusinessType())) {
					productLine.setCode(this.getCode(productLine.getBusinessType()));
				}else {
					productLine.setCode(pl.getCode());
				}
			}
			// 更新产品线
			productLineDao.updateProductLineById(productLine);
			//删除原数据
			productLineDepartmentDao.deleteProductLineDepartmentByPlId(productLine.getId());
		}
		// 更新/添加部门
		List<ProductLineDepartment> listDp = input.getProductLineDepartmentList();
		if (listDp != null && listDp.size() >= 1) {
			Iterator<ProductLineDepartment> it = listDp.iterator();
			while (it.hasNext()) {
				ProductLineDepartment p = it.next();
				if (StringUtil.isBlack(p.getDepartmentId())) {
					it.remove();
				} else {
					p.setId(IdCreater.getId());
					p.setProductLineId(id);
				}

			}
			productLineDepartmentDao.insertProductLineDepartmentList(listDp);
		}

		out.setStatus(Constant.TRUE);
		return out;
	}
	
	/*
	 * 根据业务类型生成code
	 */
	private String getCode(String businessType) throws CheckParamException {
		//获取Code
		String type = "";
		if(Constant.BUSSNESS_TYPE_A.equals(businessType)) {
			type = "A";
		}else if(Constant.BUSSNESS_TYPE_B.equals(businessType)){
			type = "B";
		}else if(Constant.BUSSNESS_TYPE_C.equals(businessType)) {
			type = "C";
		}else {
			throw new CheckParamException("业务类型类型错误");
		}
		//补0
		String productLineCode = codeCreateServ.createCode(type) + "";
		int length = Constant.PRODUCT_LINE_CODE_LENGTH-productLineCode.length();
		if(productLineCode.length() < Constant.PRODUCT_LINE_CODE_LENGTH) {
			for(int i=0; i< length; i++) {
				productLineCode = "0"+productLineCode;
			}
		}
		
		return type+productLineCode;
	}

	/**
	 * 查询
	 */
	@Override
	public QueryProductLineOutput queryProductLine(QueryProductLineInput input) {

		QueryProductLineOutput out = new QueryProductLineOutput();
		
		if(input == null) {
			out.setStatus(Constant.FALSE);
			out.setMsg("数据为空");
			return out;
		}
		if(input.getProductLineQuery() == null) {
			input.setProductLineQuery(new ProductLineQuery());
		}
		
		if(!StringUtil.isBlack(input.getProductLineQuery().getId())) {
			input.getProductLineQuery().setOrderName(null);
			input.getProductLineQuery().setOrderType(null);
			input.setStart(null);
			input.setLength(null);
		}

		PageParams<ProductLineQuery> params = new PageParams<ProductLineQuery>();
		params.setPageParam(input.getStart(), input.getLength());
		ProductLineQuery pq = input.getProductLineQuery();
		if(pq == null) {
			pq = new ProductLineQuery();
		}
		params.setParam(pq);

		List<ProductLine> listPl = productLineDao.selectProductLine(params);

		// 查询部门
		Map<String, List<ProductLineDepartment>> productLineDepartmentList = new HashMap<String, List<ProductLineDepartment>>();
		for (ProductLine p : listPl) {
			List<ProductLineDepartment> listD = productLineDepartmentDao.selectByProductLineId(p.getId());
			productLineDepartmentList.put(p.getId(), listD);
		}

		out.setDataList(listPl);
		out.setProductLineDepartmentList(productLineDepartmentList);
		out.setTotals(params.getPageQueryResult().getTotal());
		out.setTotalPages(params.getPageQueryResult().getTotalPage());

		out.setStatus(Constant.TRUE);
		return out;
	}

	/**
	 * 启用/停用
	 */
	@Override
	public PubOutputDto startUseProductLine(StartUseProductLineInput input) {

		PubOutputDto out = new PubOutputDto();

		String id = input.getProductLine();

		if(!(Constant.START_USE_1.equals(input.getType()) || Constant.STOP_USE_2.equals(input.getType()))) {
			out.setStatus(Constant.FALSE);
			out.setMsg("状态错误");
			return out;
		}
		
		if (Constant.START_USE_1.equals(input.getType())) {
			ProductLine p = productLineDao.selectProductLineById(id);
			if (p == null || Constant.FORBID_USE.equals(p.getStartUse())) {
				out.setStatus(Constant.FALSE);
				out.setMsg("产线配置未完成，不能启用");
				return out;
			}
		}

		ProductLine p = new ProductLine();
		p.setId(id);
		p.setStartUse(input.getType() + "");
		p.setEffDate(new Timestamp(System.currentTimeMillis()));
		productLineDao.updateProductLineByField(p);

		out.setStatus(Constant.TRUE);
		return out;
	}

	/**
	 * 配置秘钥
	 */
	@Override
	public PubOutputDto configProductLineKey(ConfigProductLineKeyInput input) throws CheckParamException {

		ProductLineKey plk = input.getProductLineKey();

		CheckNull ck = new CheckNull();
		ck.checkNull(plk, "productLine", "secretKey");

		ProductLineKey pl = productLineKeyDao.selectProductLineKeyByPlId(plk.getProductLine());
		if (pl != null) {
			plk.setId(pl.getId());
			productLineKeyDao.updateProductLineKeyById(plk);
		} else {
			plk.setId(IdCreater.getId());
			productLineKeyDao.insertProductLineKey(plk);
			
			//更新startUse为停用状态
			ProductLine productLine = new ProductLine();
			productLine.setId(plk.getProductLine());
			productLine.setStartUse(Constant.STOP_USE_2+"");
			productLineDao.updateProductLineByField(productLine);
		}

		PubOutputDto out = new PubOutputDto();
		out.setStatus(Constant.TRUE);
		return out;
	}

	/**
	 * 创建秘钥
	 */
	@Override
	public CreateProductLineKeyOutput createProductLineKey() {

		CreateProductLineKeyOutput out = new CreateProductLineKeyOutput();
		out.setData(IdCreater.getId());
		out.setStatus(Constant.TRUE);

		return out;
	}

	/**
	 * 根据产品线编码查询秘钥
	 */
	@Override
	public ProductLineKey queryKeyByProductLineCode(String code) {
		
		return productLineKeyDao.selectByProductLineCode(code);
	}
	/**
	 * 根据产品线id查询秘钥
	 */
	@Override
	public ConfigProductLineKeyOutput queryKeyByProductLineId(String id) {
		ConfigProductLineKeyOutput out = new ConfigProductLineKeyOutput();
		
		ProductLineKey productLineKey = productLineKeyDao.selectByProductLineId(id);
		out.setData(productLineKey);
		out.setStatus(true);
		return out;
	}
	/**
	 * 根据code查产品线
	 */
	@Override
	public ProductLine queryByCode(String code) {
		return productLineDao.selectProductLineByCode(code);
	}
}
